package chapter21.section2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @date 2020-11-05 下午3:17
 */
public class SimplePriorities implements Runnable {
    private final int priority;
    private int countDown = 5;
    private volatile double d;

    public SimplePriorities(int priority) {
        this.priority = priority;
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            exec.execute(new SimplePriorities(Thread.MIN_PRIORITY));
        }

        exec.execute(new SimplePriorities(Thread.MAX_PRIORITY));
        exec.shutdown();
    }

    @Override
    public String toString() {
        return "SimplePriorities{" + Thread.currentThread() + ":" +
                "priority=" + priority +
                '}';
    }

    @Override
    public void run() {
        Thread.currentThread().setPriority(priority);
        while (true) {
            for (int i = 0; i < 100000; i++) {
                d += (Math.PI + Math.E) / (double) i;
                if (i % 1000 == 0) {
                    Thread.yield();
                }
            }

            System.out.println(this);
            if (--countDown == 0) {
                return;
            }
        }
    }
}
